import { Button, Form, Input, message, Select, Upload } from 'antd'
import React, { useEffect, useState } from 'react'
import Layout from '../core/Layout'
import { UploadOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { getCategory } from '../../store/actions/category.action';
import { useSelector } from '../../hooks/useSelector';
import { RcFile } from 'antd/lib/upload';
import axios from 'axios';
import { API } from '../../config';
import { isAuth } from '../../helpers/auth';
import { Jwt } from '../../store/models/auth';

const AddProduct = () => {
  const dispatch = useDispatch()
  const [file, setFile] = useState<RcFile>()
  const category = useSelector(state=>state.category)
  useEffect(()=>{
    dispatch(getCategory())
  },[])
  const addProductFrom = () => {
    const porps = {
      accept: 'image/*',
      beforeUpload(file:RcFile){
        console.log(file)
        setFile(file)
        return false
      }
    }
    return (
      <Form onFinish={onFinish}>
        <Form.Item>
          <Upload {...porps}>
            <Button icon={<UploadOutlined />}>上传商品封面</Button>
          </Upload>
        </Form.Item>
        <Form.Item name={'name'} label='商品名称'>
          <Input/>
        </Form.Item>
        <Form.Item name={'description'} label='商品描述'>
          <Input/>
        </Form.Item>
        <Form.Item name={'price'} label='商品价格'>
          <Input/>
        </Form.Item>
        <Form.Item name={'category'} label='所属分类'>
          <Select placeholder='请选择分类' allowClear>
            {
              category.category.result.map(item=>(
                <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>
              ))
            }
          </Select>
        </Form.Item>
        <Form.Item name={'quantity'} label='商品数量'>
          <Input/>
        </Form.Item>
        <Form.Item name={'shipping'} label='是否需要运输'>
          <Select>
            <Select.Option value={'1'}>是</Select.Option>
            <Select.Option value={'0'}>否</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type='primary' htmlType='submit'>添加商品</Button>
        </Form.Item>
      </Form>
    )
  }
  const { user,token } = isAuth() as Jwt
  const onFinish = (product:any) => {
    const formdata = new FormData()
    for (const key in product) {
      formdata.set(key,product[key])
    }
    if(file){
      formdata.set('photo',file)
    }
    axios.post(`${API}/product/create/${user._id}`,formdata,{
      headers: {
        Authorization: `Bearer ${token}`
      }
    }).then(()=>{
      message.success('商品添加成功')
    },()=>{
      message.success('商品添加失败')
    })
  }
  return (
    <Layout title='添加上商品' subTitle=''>
      {addProductFrom()}
    </Layout>
  )
}

export default AddProduct